package com.qiangesoft.ai.tongyi.controller;

import com.qiangesoft.ai.tongyi.service.TongYiService;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * 通义AI控制层
 *
 * @author qiangesoft
 * @date 2024-10-10
 */
@RestController
@RequestMapping("/ai")
public class TongYiController {

    @Autowired
    private TongYiService tongYiService;

    @GetMapping("/answer")
    public String answer(@RequestParam(value = "message", defaultValue = "讲个小笑话") String message) {
        return tongYiService.answer(message);
    }

    @GetMapping("/streamAnswer")
    public Flux<ChatResponse> streamAnswer(@RequestParam(value = "message", defaultValue = "讲个小笑话") String message) {
        return tongYiService.streamAnswer(message);
    }

    @GetMapping("/image")
    public ResponseEntity<byte[]> image(@RequestParam(value = "message") String message) {
        byte[] fileContent = tongYiService.genImg(message);

        // 设置响应头，指定文件名
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDisposition(ContentDisposition.attachment().filename("image.png").build());

        return ResponseEntity.ok().headers(headers).body(fileContent);
    }

    @GetMapping("/audio")
    public ResponseEntity<byte[]> audio(@RequestParam(value = "message") String message) {
        byte[] fileContent = tongYiService.genAudio(message);

        // 设置响应头，指定文件名
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDisposition(ContentDisposition.attachment().filename("audio.mp3").build());

        return ResponseEntity.ok().headers(headers).body(fileContent);
    }

}